<?php
require 'vendor/autoload.php';

class TrendManager{
	
	private $searcher;
	private $textCleaner;
	private $newsManager;
	private $SortedTrendingWordsArray;

	function __construct($searcher, $textCleaner,$newsManager){
		$this->searcher = $searcher;
		$this->textCleaner = $textCleaner;
		$this->newsManager=$newsManager;
	}

	function getTrendingNews(){
		$NewsToReturn  = 30;
		$trendingWordsArray = $this->SortedTrendingWordsArray;
		$trendingNewsArray = array();
		$NonRelatedNewsFound = 0;
		$index = 0;
		$trendingWords = count($trendingWordsArray['words']);
		$metodo = 'peso';
		$similarNewsAlreadyListed=false;
		while($NonRelatedNewsFound < $NewsToReturn && $index < $trendingWords){
			$trendingword = $trendingWordsArray['words'][$index];
			$newsArray = $this->searcher->searchOnDBForTrendingNews($trendingword,$metodo);
			if (count($newsArray) > 0){
				$isValidNews = ($newsArray[0] instanceof News);
				if ($isValidNews){
					$news = $newsArray[0];
					if (count($trendingNewsArray) > 0){
						$similarNewsAlreadyListed = $this->newsIsSimilarToTheOnesInArray($news,$trendingNewsArray);
					}
					if (!$similarNewsAlreadyListed){
						$trendingNewsArray[]=$news;
					}
				}
			}
			$NonRelatedNewsFound = count($trendingNewsArray);
			$index++;
		}
		return($trendingNewsArray);
	}

	function newsIsSimilarToTheOnesInArray($newsToCheck,$newsArray){
		$similar = false;
		$j = 0;
		$limit  = count($newsArray);
		while ($j < $limit && !$similar){
			
			$similar = $this->newsAreRelated($newsToCheck->getTitle(),$newsArray[$j]->getTitle());
			$j++;
		}
		return ($similar);
	}
	
	function getTrendingWords(){
		$arrayAllNews = $this->newsManager->getAllLatestNewsFromDB();
		$arrayAllTitles = $this->getNewsTitles($arrayAllNews);
		$filteredArray = $this->textCleaner->cleanArray($arrayAllTitles);
		$trendingWordsArray = $this->keyWordsCount($filteredArray);
		$SortedTrendingWordsArray = $this->sortTWArray($trendingWordsArray);
		$this->SortedTrendingWordsArray=$SortedTrendingWordsArray;
		return($SortedTrendingWordsArray);
	}

	function keyWordsCount($arrayTitles){

		$trendingWordsArray = array(
				"words" => array(),
				"hits" => array(),
		);
		foreach($arrayTitles as $title){
			$titleWordsArray = explode(" ",$title);
			$titleWordsArray = $this->checkAndCombineWordArray($titleWordsArray);
			foreach($titleWordsArray as $word){
				$wordFound = false;
				$sizeLimit = count($trendingWordsArray["words"]);
				$wordSize = strlen($word);
				if ($wordSize < 4){
				}
				else{
					if ($sizeLimit == 0){
						$trendingWordsArray["words"][0] = $word;
						$trendingWordsArray["hits"][0] = 1;
					}
					else{
						$index = 0;
						while(!$wordFound && $index < $sizeLimit){

							if ($word == $trendingWordsArray["words"][$index]){
								$wordFound = true;
								$trendingWordsArray["hits"][$index] = $trendingWordsArray["hits"][$index] + 1;
							}
							$index++;
						}
							
						if (!$wordFound){
							$trendingWordsArray["words"][] = $word;
							$trendingWordsArray["hits"][] = 1;
						}
					}
				}
			}
		}
		return($trendingWordsArray);
	}

	function sortTWArray($array){
		$count = count($array["hits"]);
		for($i=1; $i<$count; $i++){
			$tmp = $array["hits"][$i];
			$tmpW = $array["words"][$i];
			for ($j=$i-1; $j>=0 && $array["hits"][$j] < $tmp; $j--){
				$array["hits"][$j+1] = $array["hits"][$j];
				$array["words"][$j+1] = $array["words"][$j];
			}
			$array["hits"][$j+1] = $tmp;
			$array["words"][$j+1] = $tmpW;
		}
		return $array;
	}
	
	function newsAreRelated($title,$otherTitle){
		$csvData = file_get_contents('properties/unwantedWords.csv');
		$unwantedWordsArray = str_getcsv($csvData,',');
		$relationshipLimit = 3;
		$newsKWs =  $this->checkAndCombineWordArray(explode(" ",$title));
		$otherNewsKW =  $this->checkAndCombineWordArray(explode(" ",$otherTitle));
		$wordsInCommon = array_uintersect($newsKWs, $otherNewsKW, 'strcasecmp');
		if (count($wordsInCommon) < $relationshipLimit){
			$result = false;
		}else{
			$result = true;
		}
		return ($result);
	}
	
	function getNewsTitles($arrayNews){
		$arrayTitles = array();
		$index = 0;
		foreach ($arrayNews as $news) {
			$title = $news->getTitle();
			$arrayTitles[$index] = $title;
			$index++;
		}
		return ($arrayTitles);
	}
	
function checkAndCombineWordArray($titleWordsArray){
		$combinedTitleWordsArray = array();
		$limit = count ($titleWordsArray);
		$index=0;
		while ($index<$limit){
			$currentWord = $this->textCleaner->removeUnwantedCharsFromStringForRegex($titleWordsArray[$index]);
			$result = preg_match_all('"([A-Z][a-zA-Z]*)+[^:]$"', $currentWord, $arr, PREG_PATTERN_ORDER);
			if ($result > 0){
				$index++;
				$combinedWord=$currentWord;
				while ($result > 0 && ($index +1) <= $limit){
					$nextWord = $this->textCleaner->removeUnwantedCharsFromStringForRegex($titleWordsArray[$index]);
					$result = preg_match_all('"([A-Z][a-zA-Z]*)+[^:]$"', $nextWord, $arr, PREG_PATTERN_ORDER);
					if ($result > 0){
							$combinedWord = $combinedWord . " " . $this->textCleaner->removeUnwantedTermsFromString($nextWord);
							$index++;
					}
					else{
						//Si entre aca es porque o no empieza con mayusculas o termina con ":"
						$result = preg_match_all('"([A-Z][a-zA-Z]*)+"', $nextWord, $arr, PREG_PATTERN_ORDER);
						if($result > 0){
							$combinedWord = $combinedWord . " " . $this->textCleaner->removeUnwantedTermsFromString($nextWord);
							//Fuerzo result a 0 porque se que aca comienza una cita textual (despues de los :)
							$result=0;
						}
						else{
							//Vuelvo el indice uno para atras, porque es una palabra que no tiene que ver con la "Frase"
							$index--;
						}
						
						
					}
				}
			}
			else{
				//Si entre aca es porque o no empieza con mayusculas
				$combinedWord = $this->textCleaner->removeUnwantedTermsFromString($currentWord);
			}
			$index++;
			if (strlen($combinedWord) > 3){
				$combinedTitleWordsArray[] = $combinedWord;
			}
		}
		
		return ($combinedTitleWordsArray);
	}
}

?>